const express = require('express')
const moment = require('moment')
const { resolve } = require('path')
const fs = require('fs')
const { verifyToken } = require('../db/crud/loginFn')
const router = express.Router()
const advModel = require('../db/model/advs')
const tokenManger = require('../utils/tokenManger')
const { log } = require('console')
async function middleWare(req, res, next) {
  // 验证token
  const token = req.get('authorization')
  const admin = await verifyToken(token)
  if (admin) {
    const result = tokenManger.jwtDecode(admin.token)
    if (Date.now() < result.expires) {
      next()
    } else {
      res.send({ success: false, msg: 'token失效请重新登录' })
    }
  } else {
    res.send({ success: false, msg: 'token失效请重新登录' })
  }
}
router.post('/addAdv', middleWare, async (req, res) => {
  const fields = req.fields
  const files = req.files
  const { advTitle, advCategory, advLink } = fields
  const { file } = files

  const advAvatar =
    'http://localhost:5000/uploadDir/' + file.path.split('\\')[2]

  try {
    await advModel.create({
      advTitle,
      advAvatar,
      advCategory,
      advLink,
    })
    const data = await advModel.find()
    res.send({ success: true, msg: '广告图片添加成功', data })
  } catch (error) {
    res.send({ success: true, msg: '广告图片添加失败' })
  }
})

router.get('/getAdvs', middleWare, async (req, res) => {
  try {
    const result = await advModel.find()
    res.send({ success: true, data: result })
  } catch (error) {
    res.send({ success: false, msg: '广告图片查找失败,请稍后在试' })
  }
})
router.post('/deleteAdv', middleWare, async (req, res) => {
  const { id } = req.fields
  try {
    const adv = await advModel.findOne({ _id: id })
    let path = adv.advAvatar.replace('http://localhost:5000/uploadDir/', '')
    path = resolve(__dirname, '../public/uploadDir', path)
    await advModel.deleteOne({ _id: id })
    fs.unlinkSync(path)
    const result = await advModel.find()
    res.send({ success: true, msg: '广告删除成功', data: result })
  } catch (error) {
    res.send({ success: false, msg: '广告删除失败,请稍后在试' })
  }
})
router.post('/updateAdv', middleWare, async (req, res) => {
  const { advTitle, advCategory, advLink, id } = req.fields
  const { file } = req.files

  if (file.size) {
    const advAvatar =
      'http://localhost:5000/uploadDir/' + file.path.split('\\')[2]
    try {
      // 删除之前的照片
      const adv = await advModel.findOne({ _id: id })
      const filename = adv.advAvatar.replace(
        'http://localhost:5000/uploadDir/',
        ''
      )
      await advModel.updateOne(
        {
          _id: id,
        },
        {
          $set: {
            advTitle,
            advCategory,
            advLink,
            advAvatar,
            advMotifyDate: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
          },
        }
      )

      const path = resolve(__dirname, '../public/uploadDir', filename)
      fs.unlinkSync(path)

      const result = await advModel.find()
      res.send({ success: true, data: result, msg: '修改成功' })
    } catch (error) {
      res.send({ success: false, msg: '修改失败,请稍后再试' })
    }
  } else {
    // 删除错误存储的无后缀名文件
    const path = resolve(
      __dirname,
      '../public/uploadDir',
      file.path.split('\\')[2]
    )
    fs.unlinkSync(path)
    try {
      await advModel.updateOne(
        {
          _id: id,
        },
        {
          $set: {
            advTitle,
            advCategory,
            advLink,
            advMotifyDate: moment(Date.now()).format('YYYY-MM-DD HH:mm:ss'),
          },
        }
      )
      const result = await advModel.find()
      res.send({ success: true, data: result, msg: '修改成功' })
    } catch (error) {
      res.send({ success: false, msg: '修改失败,请稍后再试' })
    }
  }
})

router.get('/getAdvOne', middleWare, async (req, res) => {
  const { id } = req.query
  try {
    const result = await advModel.findOne({ _id: id })
    res.send({ success: true, data: result })
  } catch (error) {
    res.send({ success: false, msg: '广告图片查找失败,请稍后在试' })
  }
})

module.exports = router
